<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
class BestSellersComponent
{
	function BestSellersComponent()
	{
	}

	function action(&$params, $action)
	{
		return $this->query($params);
	}

	function query(&$params) 
	{
		$handle = get_class($this);
		$language_id = (int)$params['languageId'];
		$category_id = (int)$params['categoryId'];
		$manufacturer_id = (int)$params['manufacturerId'];

		$cache_id = $language_id . '_' . $category_id . '_' . $manufacturer_id;
		$json = read_cache($cache_id, $handle);
		if ($json)
		{
			if ($json == 'null') return null;
			else return json_decode($json, true);
		}

		$subParams['handle'] = $handle;
		$subParams['languageId'] = $language_id;
		$subParams['categoryId'] = $category_id;
		$subParams['inc_subcat'] = 1;
		$subParams['manufacturerId'] = $manufacturer_id;
		$subParams['max_rows'] = MAX_DISPLAY_BESTSELLERS;
		$subParams['and_where'] = ' and p.products_ordered != 0';
		$subParams['orderby'] = 'p.products_ordered desc, pd.products_name';
		
		require_once('includes/components/ProductsSearchSubComponent.php');
		$subComponent = new ProductsSearchSubComponent();
		$value = $subComponent->query($subParams);

		//always return something, even if nothing found in category.
		if ($value{'BestSellersComponent'}{0}{'id'} == null)
		{
			$subParams['categoryId'] = 0;
			$value = $subComponent->query($subParams);
		}
					
		if ($value != null) $json = json_encode($value);
		write_cache($json, $cache_id, $handle);

		return $value;
	}
}
?>
